/**
 * @(#) OverView.as
 *
 * @date		2009. 04. 20.
 * @version		1.0
 * @author		Jo, ChangHun
 * @description	연말정산 메인 view - Mediator
 * 				연말정산 - 탭1 총소득액 Presentation Logic을 관리 
 */
package com.skt.common_hr.yearadjustment.view
{
	import com.skt.common_hr.common.PsHrAlert;
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.yearadjustment.YearAdjustmentFacade;
	import com.skt.common_hr.yearadjustment.events.PriorAreaItemEvent;
	import com.skt.common_hr.yearadjustment.model.BizNumValidProxy;
	import com.skt.common_hr.yearadjustment.model.PrevJobPlaceProxy;
	import com.skt.common_hr.yearadjustment.model.TotalIncomeProxy;
	import com.skt.common_hr.yearadjustment.model.vo.PrevJobPlaceDetailVO;
	import com.skt.common_hr.yearadjustment.model.vo.PrevJobPlaceVO;
	import com.skt.common_hr.yearadjustment.view.components.YearAdjustmentView;
	import com.skt.common_hr.yearadjustment.view.components.popTotalIncome;
	import com.wcl.utils.DateUtil;
	import com.wcl.utils.StringUtil;
	
	import flash.events.Event;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;
	
	

	public class popTotalIncomeMediator extends Mediator
	{
		public static const NAME:String = "popTotalIncomeMediator"; 

		public var v_year:String = "";
		[Bindable] public var v_enable:Boolean = true;

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function popTotalIncomeMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
            view.callLater(initView);
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
 		public function initView():void
 		{
 			view.addEventListener(popTotalIncome.OkInput, onOkInput);
 			view.addEventListener(popTotalIncome.CancelInput, onCancelInput);
 			view.addEventListener(popTotalIncome.AddItem, onAddItem);
 			view.addEventListener(PriorAreaItemEvent.PRIORAREA_ITEM_DEL, onItemDelete);
 			view._isEnable = v_enable;
 			
 			loadPrevJobPlaceTypes();
 			//onSelectPriorArea();
 		}
 		
		private function loadPrevJobPlaceList():void{
 			var proxy:PrevJobPlaceProxy = facade.retrieveProxy(PrevJobPlaceProxy.NAME) as PrevJobPlaceProxy;
 			proxy.load(Variables.yearPernr, v_year); 	
 		}
 		
 		private function loadPrevJobPlaceTypes():void
 		{
 			var proxy:PrevJobPlaceProxy = facade.retrieveProxy(PrevJobPlaceProxy.NAME) as PrevJobPlaceProxy;
 			proxy.loadDetail();
 		}
 		
 		private function onSelectPriorArea():void{
 			var proxy:TotalIncomeProxy = facade.retrieveProxy(TotalIncomeProxy.NAME) as TotalIncomeProxy;
 			proxy.load(Variables.yearPernr, v_year); 	
 		}
 		
 		private function onAddItem(event:Event):void{
 			if(view.jobPlaceList.length<5) {
	 			//var vo:TotalIncomeVO = new TotalIncomeVO();
	 			//view.priorAreaData.addItem(vo);
				//PsHrAlert.showMessage("length: " + view.jobPlaceList.length);

	 			var vo:PrevJobPlaceVO = getBlankJobPlace();
	 			view.jobPlaceList.addItem(vo);
	 			vo.no =  view.jobPlaceList.length; 
	 			setTabIndexID = setInterval( setTabIndex, 500);
 			}
 			else {
 				PsHrAlert.showMessage("종(전)근무지는 5개까지 입력할 수 있습니다.");
 			}
 		}
 		
 		private var setTabIndexID:int;
 		private function setTabIndex():void
 		{
 			view.tnView.selectedIndex = view.jobPlaceList.length-1;
 			clearInterval(setTabIndexID);
 		}
 		
 		private function getBlankJobPlace():PrevJobPlaceVO
 		{
 			var proxy:PrevJobPlaceProxy = facade.retrieveProxy(PrevJobPlaceProxy.NAME) as PrevJobPlaceProxy;
 			var vo:PrevJobPlaceVO = new PrevJobPlaceVO();
 			vo.detail = new ArrayCollection();
 			if(proxy != null) {
 				for each(var srcType:PrevJobPlaceDetailVO in proxy.dataTypes) {
					 var type:PrevJobPlaceDetailVO = srcType.clone();
					 vo.detail.addItem(type);
 				}
 			}
 			return vo;
 		}
 		
 		
 		private function onItemDelete(event:PriorAreaItemEvent):void{
			//view.tnView.selectedIndex = 0; 			
 			//view.priorAreaData.addEventListener(CollectionEvent.COLLECTION_CHANGE, onArrChange);
 			view.jobPlaceList.removeItemAt(event.itemIdx);
 			for(var i:int=0; i<view.jobPlaceList.length; i++) {
 				(view.jobPlaceList.getItemAt(i) as PrevJobPlaceVO).no = i+1;
 			}
 			//view.priorAreaData.removeItemAt(event.itemIdx);
 		}
 		
 		private function onArrChange(event:Event):void{
 			view.tnView.selectedIndex = 1;
 		}
 		
 		private function onOkInput(event:Event):void
 		{
 			if(validate()) {
 				var proxy:PrevJobPlaceProxy = facade.retrieveProxy(PrevJobPlaceProxy.NAME) as PrevJobPlaceProxy;
 				proxy.save(Variables.yearPernr, v_year, getHeadTable(), getItemTable());
 			}
 		}
 		
 		private function getHeadTable():Array
 		{
 			var arrHead:Array = new Array()
 			
 			for each(var vo:PrevJobPlaceVO in view.jobPlaceList) {
 				var tmp:Object = new Object();
 				tmp.SEQNR = vo.SEQNR;
 				tmp.BIZNO = vo.BIZNO;
 				tmp.COMNM = vo.COMNM;
 				tmp.TXPAS = vo.TXPAS;
 				
 				tmp.PABEG = (vo.PABEG!=null) ? DateUtil.toBasicString(vo.PABEG) : "";
 				tmp.PAEND = (vo.PAEND!=null) ? DateUtil.toBasicString(vo.PAEND) : "";
  				tmp.EXBEG = (vo.EXBEG!=null) ? DateUtil.toBasicString(vo.EXBEG) : "";
 				tmp.EXEND = (vo.EXEND!=null) ? DateUtil.toBasicString(vo.EXEND) : "";
 				arrHead.push(tmp);
 			}
 			return arrHead;
 		}
 		
 		
 		private function getItemTable():Array
 		{
  			var arrItem:Array = new Array()
 			
 			for each(var vo:PrevJobPlaceVO in view.jobPlaceList) {
 				for each(var item:PrevJobPlaceDetailVO in vo.detail) {
 					arrItem.push(item)
 				}
 			}
 			return arrItem;
		}
 
 		private function validate():Boolean
 		{
 			for each(var vo:PrevJobPlaceVO in view.jobPlaceList) {
 				if(vo.BIZNO == null || StringUtil.trim(vo.BIZNO).length < 10) {
 					PsHrAlert.showMessage("사업자 번호를 바르게 입력해 주십시오.");
 					return false;
 				}
 				if(vo.COMNM == null || StringUtil.trim(vo.COMNM).length < 1) {
 					PsHrAlert.showMessage("상호를 바르게 입력해 주십시오.");
 					return false;
 				}
 				if(vo.PABEG == null || vo.PAEND == null) {
 					PsHrAlert.showMessage("근무기간을 바르게 입력해 주십시오.");
 					return false;
 				}
 				vo.SEQNR = vo.no.toString();
 				for each(var item:PrevJobPlaceDetailVO in vo.detail) {
 					item.SEQNR = vo.SEQNR;
 				}
 			}
 			return true;
 		} 
 		
 		
 		
 		/*
 		private function onOkInput(event:Event):void{
 			
 			var proxy:TotalIncomeProxy = facade.retrieveProxy(TotalIncomeProxy.NAME) as TotalIncomeProxy;
 			
 			var detailList:Array = new Array();
 			trace("view.priorAreaData : " + view.priorAreaData.length);

 			for(var i:int=0; i < view.priorAreaData.length; i++){

//shgoo 2010.01.18
				//사업자 번호 체크로직 추가 	
				if(	String(view.priorAreaData[i].PCBUS).indexOf("-") >= 0 ) {
		 			PsHrAlert.showMessage("사업자 번호가 올바르지 않습니다.");
	 				return;
 				}
//////////////// 		
	 			if(view.priorAreaData[i].PCBUS.length != 0 && view.priorAreaData[i].PCBUS.length < 10){
	 				PsHrAlert.showMessage("사업자 번호가 올바르지 않습니다.");
	 				return;
	 			}
 				
 			}
	 		for each(var rec:TotalIncomeVO in view.priorAreaData)
	 		{
			 	rec.PCSAL /= 100;
			 	rec.PCBON /= 100;
			 	rec.PCOUT /= 100;
			 	rec.PCOVR /= 100;
			 	rec.PCOTH /= 100;
			 	rec.PCNPM /= 100;
			 	rec.PCMED /= 100;
			 	rec.PCEIM /= 100;
			 	rec.PCINT /= 100;
			 	rec.PCRET /= 100;
			 	rec.PCFOR /= 100;
				rec.PCSPT /= 100;
				
	 			detailList.push(rec);
	 		}
 			
 			proxy.save(Variables.yearPernr, v_year, detailList); 	
 		}
 		*/
 		private function onCancelInput(event:Event):void
 		{
 			facade.removeMediator(popTotalIncomeMediator.NAME);
 			PopUpManager.removePopUp(view);
 		}
 		
 		/***
 		 * 저장실패시 /100한 금액 이전으로 return 
 		 * **/
 		private function returnAmt():void{
 			for(var i:int = 0; i < view.priorAreaData.length; i++)
	 		{
	 			view.priorAreaData[i].PCSAL *= 10 * 10;
			 	view.priorAreaData[i].PCBON *= 10 * 10;
			 	view.priorAreaData[i].PCOUT *= 10 * 10;
			 	view.priorAreaData[i].PCOVR *= 10 * 10;
			 	view.priorAreaData[i].PCOTH *= 10 * 10;
			 	view.priorAreaData[i].PCNPM *= 10 * 10;
			 	view.priorAreaData[i].PCMED *= 10 * 10;
			 	view.priorAreaData[i].PCEIM *= 10 * 10;
			 	view.priorAreaData[i].PCINT *= 10 * 10;
			 	view.priorAreaData[i].PCRET *= 10 * 10;
			 	view.priorAreaData[i].PCFOR *= 10 * 10;
				view.priorAreaData[i].PCSPT *= 10 * 10; 
	 		}
 		}
 		

		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return [
					YearAdjustmentFacade.LOAD_TOTALINCOM_AREA_COMPLETE,
					YearAdjustmentFacade.LOAD_TOTALINCOM_AREA_FAILED,
					YearAdjustmentFacade.SAVE_TOTALINCOM_AREA_COMPLETE,
					YearAdjustmentFacade.SAVE_TOTALINCOM_AREA_FAILED,
					YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_COMPLETE,
					YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_FAILED,
					PrevJobPlaceProxy.LOAD_PREV_JOBPLACE_LIST_COMPLETE,
					PrevJobPlaceProxy.LOAD_PREV_JOBPLACE_LIST_FAILED,
					PrevJobPlaceProxy.LOAD_DATA_TYPES_COMPLETE,
					PrevJobPlaceProxy.LOAD_DATA_TYPES_FAILED,
					PrevJobPlaceProxy.SAVE_PREV_JOBPLACE_LIST_COMPLETE,
					PrevJobPlaceProxy.SAVE_PREV_JOBPLACE_LIST_FAILED
					];
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			switch(note.getName()) 
			{
				case PrevJobPlaceProxy.LOAD_DATA_TYPES_COMPLETE:
					loadPrevJobPlaceList();
					break;
					
				case PrevJobPlaceProxy.LOAD_PREV_JOBPLACE_LIST_COMPLETE:
					onLoadJobPlaceList(note.getBody() as PrevJobPlaceProxy);
					break;
				
				case PrevJobPlaceProxy.SAVE_PREV_JOBPLACE_LIST_COMPLETE:
					onCancelInput(null);
					facade.sendNotification(YearAdjustmentFacade.RELOAD_BASIC_DATA);
					//facade.sendNotification(YearAdjustmentView.CHECK_REQ_TOTALINCOME);
					break;
				case PrevJobPlaceProxy.SAVE_PREV_JOBPLACE_LIST_FAILED:
					PsHrAlert.showMessage((note.getBody() as PrevJobPlaceProxy).msgStr);
					returnAmt();
					break;
										
				case YearAdjustmentFacade.LOAD_TOTALINCOM_AREA_COMPLETE:
					view.priorAreaData = (note.getBody() as TotalIncomeProxy).priorAreaData;
					break;
				case YearAdjustmentFacade.LOAD_TOTALINCOM_AREA_FAILED:
					trace("LOAD_TOTALINCOM_AREA_FAILED");
					//PsHrAlert.showMessage((note.getBody() as TotalIncomeProxy).msgStr);
					break;
				case YearAdjustmentFacade.SAVE_TOTALINCOM_AREA_COMPLETE:
					onCancelInput(null);
					facade.sendNotification(YearAdjustmentFacade.RELOAD_BASIC_DATA);
					//facade.sendNotification(YearAdjustmentView.CHECK_REQ_TOTALINCOME);
					break;
				case YearAdjustmentFacade.SAVE_TOTALINCOM_AREA_FAILED:
					trace(" SAVE_TOTALINCOM_AREA_FAILED ");
					PsHrAlert.showMessage((note.getBody() as TotalIncomeProxy).msgStr);
					break;	
//shgoo 2010.01.11					
				case YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_COMPLETE:	//사업자 등록 번호 유효성 체크 성공
					//항목 추가
//					addItem();
					break;
				case YearAdjustmentFacade.LOAD_BIZ_NUM_VALID_FAILED:	//사업자 등록 번호 유효성 체크 에러
					PsHrAlert.showMessage((note.getBody() as BizNumValidProxy).msgStr);
					break;
///////////////////////			
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
 		
		private function onLoadJobPlaceList(proxy:PrevJobPlaceProxy):void
		{
			//PsHrAlert.showMessage("loaded data : " + proxy.prevJobPlaceList.length);
			if(proxy.prevJobPlaceList.length>0) {
				view.jobPlaceList = proxy.prevJobPlaceList;
			}
			else if(view._isEnable) {
				var arr:ArrayCollection = new ArrayCollection();
				var vo:PrevJobPlaceVO = getBlankJobPlace();
				vo.no = 1;
				arr.addItem( vo );
				view.jobPlaceList = arr;
			}
		}
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():popTotalIncome
        {
            return viewComponent as popTotalIncome;
        }
	}
}